#!/usr/bin/env python
# encoding: utf-8
# @Time    : 2020/4/22 10:07
# @Author  : Mr. Cui
# @File    : views.py
# @Software: PyCharm
from flask import Blueprint,request,render_template
from concurrent.futures import ThreadPoolExecutor
from .service import *
re = Report()
#----------------
#队列处理
from celery import Celery
from celery.result import AsyncResult
from .service.ci_impl import *
from .service.task_impl import *
from flask import Flask, request, redirect, url_for

# ci = Blueprint('ci', __name__,static_folder='static',template_folder='template')
ci = Blueprint('ci', __name__,static_folder='static',template_folder='template',url_prefix='/views')
executor = ThreadPoolExecutor(1)


celery_app=Celery("ci_celery",broker='redis://192.168.2.92:6379/1',backend='redis://192.168.2.92:6379/1')
# celery_app.conf.broker_url = 'redis://192.168.2.92:6379/1'
# celery_app.conf.result_backend = 'redis://192.168.2.92:6379/1'
# CELERY_BROKER_URL = 'redis://192.168.2.92:6379/1'
# CELERY_RESULT_BACKEND = 'redis://192.168.2.92:6379/1' # 最后的数字1代表DB number
# celery_ = Celery(current_app.name, broker=CELERY_BROKER_URL,backend=CELERY_RESULT_BACKEND)

# celery_.conf.update(ci.name,CELERY_BROKER_URL)


@celery_app.task
def my_background_task(JOB_NAME, BUILD_ID):
    # 两数相加
    jenkins_run(JOB_NAME, BUILD_ID)
    # time.sleep(10)
    # return str(JOB_NAME+BUILD_ID)
    return "ci ok"

@celery_app.task
def my_background_task1(JOB_NAME, BUILD_ID):
    # 两数相加
    time.sleep(10)
    return str(JOB_NAME+BUILD_ID)

#
#
@ci.route("/sum/<arg1>/<arg2>")
def sum_(arg1, arg2):
    print(arg1, arg2)
    # 发送任务到celery,并返回任务ID,后续可以根据此任务ID获取任务结果
    result = my_background_task1.delay(int(arg1), int(arg2))
    return result.id


@ci.route("/get_result/<result_id>")
def get_result(result_id):
    # 根据任务ID获取任务结果
    result = AsyncResult(id=result_id)
    return str(result.get())

#----------------

@ci.route('report')
def report():
    JOB_NAME = request.args.get("job_name", "")
    BUILD_ID = request.args.get("build_id", "")
    data=re.get_report_data(JOB_NAME,BUILD_ID)
    if data[0] == 0:
        pass_rate = 0
    else:
        pass_rate = round(data[0] / sum(i[4] for i in data[1]), 4)

    pass_rate = str(round((1.0 - pass_rate) * 100,4)) + '%'

    return render_template('ci_report.html',JOB_NAME=JOB_NAME,BUILD_ID=BUILD_ID,repost=pass_rate,yapi=data[1],sonar=data[2],web_ui=data[3])

@ci.route('report/yapi/<JOB_NAME>/<BUILD_ID>/<case_col>')
def yapi(JOB_NAME,BUILD_ID,case_col):
    # "http://127.0.0.1:5000/ci/report/yapi/shop-api-qa.360che.com/33/%E6%B5%8B%E8%AF%95%E9%9B%862.html"
    return ci.send_static_file('html/yapi/%s/%s/%s'%(JOB_NAME,BUILD_ID,case_col))

# @ci.route('/')
# def index():
#     return "welcome to ci"

#jenkins调用的接口
@ci.route('jenkins')
def jenkins():
    """
    http://127.0.0.1:5000/ci/jenkins?job_name=shop-api-qa.360che.com&build_id=28
    :return:
    """
    JOB_NAME=request.args.get("job_name","")
    BUILD_ID=request.args.get("build_id","")
    if JOB_NAME=="":
        return "job_name不能为空"
    if BUILD_ID=="":
        return "build_id不能为空"
    #异步处理yapi接口自动化
    # executor.submit(jenkins_run,JOB_NAME,BUILD_ID)
    # result = my_background_task.delay(JOB_NAME,BUILD_ID)
    # return result.id

    jenkins_run(JOB_NAME,BUILD_ID)
    return "自动化任务提交成功，结果会发到钉钉群，请及时查看，JOB_NAME:%s,BUILD_ID:%s"%(JOB_NAME,BUILD_ID)

@ci.route('view')
def view():
    pass


# 自动化测试最新报告
@ci.route('/appreport', methods=['post', 'get'])
def appwebreport():
    pt1 = APP_Report(1)
    pt2 = APP_Report(2)
    appdata = pt1.title_url(1, 1)
    appreportlist = appdata[0]
    appnewreport = appdata[1]
    webdata = pt2.title_url(2, 2)
    webreportlist = webdata[0]
    webnewreport = webdata[1]
    return render_template('appreport.html', appnewreport=appnewreport, appreportlist=appreportlist,
                           webnewreport=webnewreport, webreportlist=webreportlist)


# APP更多报告列表
@ci.route('/TestReport/<rpttime>/<dev>/TestReport', methods=['post', 'get'])
def morerpt(rpttime, dev):
    url = "TestReport/%s/%s/TestReport.html" % (rpttime, dev)
    return render_template(url)


# web更多报告列表
@ci.route('/WebReport/<rpttime>', methods=['post', 'get'])
def webmorerpt(rpttime):
    url = "TestReport/%s" % (rpttime)
    return render_template(url)


# 以下是task_ci的控制器

@ci.route("/")
def index():
    return ci.send_static_file("html/task.html")


@ci.route("/tasklist/", methods=['POST', 'GET'])
def tasklist():
    task_impl = TaskImpl()
    return task_impl.selectAll()


@ci.route("/taskaddone", methods=['POST', "GET"])
def taskaddone():
    if request.method == "POST":
        task_list = TaskImpl()
        task_name = request.form.get("task_name")
        job_name = request.form.get("job_name")
        ding_token = request.form.get("ding_token")
        task_list.insertOne(task_name, job_name, ding_token)
        print(task_name)
    return redirect(url_for("ci.index"))


@ci.route("/deletetastone", methods=["GET"])
def deletetastone():
    try:
        task_list = TaskImpl()
        task_list.deleteTask(request.args.get("id"))
        return json.dumps({"code": "0"})
    except:
        return json.dumps({"code": "1"})


@ci.route("/querytaskci", methods=["GET"])
def query_task_ci():
    task_list = TaskImpl()
    return task_list.query_task_ci(request.args.get("id"))


@ci.route("/updatetask", methods=["POST"])
def updatetask():
    task_list = TaskImpl()
    task_name = request.form.get("task_name")
    job_name = request.form.get("job_name")
    ding_token = request.form.get("ding_token")
    task_id = request.form.get("task_id")
    task_list.update(id=task_id, task_name=task_name, job_name=job_name, status="1", ding_token=ding_token)
    return "success"


@ci.route("/selectonttask", methods=["GET"])
def selectonttask():
    task_list = TaskImpl()
    return task_list.selectOne(request.args.get("id"))


@ci.route("/add_ci", methods=["POST"])
def add_ci():
    ci_impl = CiImpl()
    id = request.form.get("id")
    case_col = request.form.get("case_col")
    yapi_url = request.form.get("yapi_url")
    ci_impl.insertOne(task_id=id, case_col=case_col, yapi_url=yapi_url)
    print(id, case_col, yapi_url)
    return "Success"


@ci.route("/del_ci", methods=["GET"])
def del_ci():
    ci_impl = CiImpl()
    ci_impl.delteOne(request.args.get("id"))
    return "delete success"


@ci.route("/q_ci_on_task", methods=["GET"])
def q_ci_on_task():
    ci_impl = CiImpl()
    print(ci_impl.selectByTask_id(request.args.get("id")))
    return ci_impl.selectByTask_id(request.args.get("id"))



# 到这儿结束






















#启动 celery
#celery -A apps.ci.views worker -l info -P eventlet
#flower -A apps.ci.views --port=5557